package models

import (
	"github.com/astaxie/beego/orm"
	"fmt"
)

type AiServers struct {
	Id       int64
	Serverip string //ip
	Descs    string //描述
}

func (a *AiServers) TableName() string {
	return TableName("servers")
}

func ServersAdd(p *AiServers) (int64 , error) {
	return orm.NewOrm().Insert(p)
}

//获取列表
func ServersGetList(page, pageSize int, tableName string, filters ...interface{}) ([]*AiServers, int64) {
	offset := (page - 1) * pageSize
	list := make([]*AiServers, 0)
	query := orm.NewOrm().QueryTable(TableName(tableName))
	//过滤 条件。
	if len(filters) > 0 {
		fmt.Println(filters[0].(string), filters[1])
		for i := 0; i < len(filters); i += 2 {
			query = query.Filter(filters[i].(string), filters[i+1])
		}
	}
	total, _ := query.Count()
	_, err := query.OrderBy("-id").Limit(pageSize, offset).All(&list)
	if err != nil {
		ErrorLog(err)
	}
	return list, total
}

//获取即时通讯 模板列表
func GetImServersList(tableName string, filters ...interface{}) ([]*AiServers, error) {
	list := make([]*AiServers, 0)
	query := orm.NewOrm().QueryTable(TableName(tableName))
	//过滤 条件。
	if len(filters) > 0 {
		fmt.Println(filters[0].(string), filters[1])
	}
	_, err := query.OrderBy("id").All(&list)

	if err != nil {
		return nil, err
	}
	return list, nil

}

//根据ID查询
func ServersGetById(id int) (*AiServers, error) {
	r := new(AiServers)
	err := orm.NewOrm().QueryTable(TableName("servers")).Filter("id", id).One(r)
	if err != nil {
		return nil, err
	}
	return r, nil
}

//更新数据库
func (a *AiServers) Update(fields ...string) error {
	if _, err := orm.NewOrm().Update(a, fields...); err != nil {
		return err
	}
	return nil
}

//删除数据库
func (a *AiServers) Delete(fields ...string) error {
	if _, err := orm.NewOrm().Delete(a, fields...); err != nil {
		return err
	}
	return nil
}